/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;

/**
 *
 * @author Juan Ortiz
 */
public abstract class DaoBase<T> {
    
    public void insertEntity(T entity) {
        EntityManager em=EMF.getEntityManager();
                        	           
            em.getTransaction().begin();
            em.persist(entity);
            em.getTransaction().commit();	 
        	em.close();
               	        	
        }             
    
    public void updateEntity(T entity) {
        EntityManager em = EMF.getEntityManager();

        em.getTransaction().begin();
        em.merge(entity);
        em.getTransaction().commit();

        em.close();
    }
    
    public void deleteEntity(T entity) {
        EntityManager em = EMF.getEntityManager();

        em.getTransaction().begin();
        em.persist(entity);
        em.remove(entity);
        em.getTransaction().commit();

        em.close();
    }
    
    protected List<T> search(String queryText, QParameter... params){
        EntityManager em = null;
		
	try {
		em = EMF.getEntityManager();
		Query q = em.createNamedQuery(queryText);

		if (params != null) {
			for (QParameter<String, Object> parameter : params) {
				q.setParameter(parameter.getKey(), parameter.getValue());
			}
		}
						
		return q.getResultList();		
	} finally {
		em.close();
	}
    }
    
    public abstract List<T> findByName(String name);
}
